<?php

namespace app\admin\controller\trade;

use app\common\controller\Backend;
use app\common\model\token\Log as Tokenlog;
use app\common\model\User;
use app\common\model\Trade;
use think\Db;
/**
 * 数字交易订单
 *
 * @icon fa fa-circle-o
 */
class Tradelog extends Backend
{
    
    /**
     * Log模型对象
     * @var \app\common\model\trade\Log
     */
    protected $model = null;
    protected $searchFields = 'trade_no';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\trade\Log;
        $this->view->assign("statusList", $this->model->getStatusList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','trade_no','buy_username','buy_trade_id','buy_num','sell_username','sell_trade_id','sell_num','exch_rate','createtime','updatetime','finishtime','status','symbol','tosymbol']);
                
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {

            if ($row['status'] != 'dispute') {
                $this->error('订单不在仲裁状态');
            }
            $res = $this->request->post("res");

            if ($res == "cancel") {
                //TODO 取消匹配订单
                
                //买家订单返还
                $trade = new Trade();
                Db::name('trade')->where('id',$row->sell_trade_id)->inc('surplusnum',$row->sell_num)->update(['status'=>1]);
                //买家订单返还
                Db::name('trade')->where('id',$row->buy_trade_id)->inc('surplusnum',$row->buy_num)->update(['status'=>1]);


                $params['status']='solve';
                $params['disputeres']=$res;
                $result = $row->allowField(true)->save($params);

                $this->success('取消匹配成功，订单已经作废');
            }else{
                $params['status']='solve';
                $params['disputeres']=$res;
                //处理仲裁功能
                $result = $row->allowField(true)->save($params);

                if ($res == 'success') {
                    $user_id = $row['sell_user_id'];
                    Db::name('trade')->where('id',$row->sell_trade_id)->inc('surplusnum',$row->sell_num)->update(['status'=>1]);
                    
                    // User::tokenlog('USD',$user_id,0,$row['sell_num'],'dispute','仲裁返还');
                }else{
                    $user_id = $row['buy_user_id'];
                    User::tokenlog('USD',$user_id,0,$row['buy_num'],'dispute','仲裁订单胜诉');
                }
                $this->success('仲裁成功');
            }
            
            $this->error('订单不正确');
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}
